package com.siebre.picclife.asynctask.service.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Optional;
import com.siebre.picclife.asynctask.TaskException;
import com.siebre.picclife.asynctask.model.Task;
import com.siebre.picclife.asynctask.model.impl.TaskEntity;
import com.siebre.picclife.asynctask.service.TaskFactory;

/**
 * 
 * @author ZhangChi
 * @since 2015年4月2日
 */
public class DefaultTaskFactory implements TaskFactory {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTaskFactory.class);
	
	private final ArgumentSerializerResolver serializerResolver;

	public DefaultTaskFactory(ArgumentSerializerResolver serializerResolver) {
		this.serializerResolver = serializerResolver;
	}

	public Task create(String type, Object descriptor) {
		TaskEntity result = new TaskEntity(type, serialize(type, descriptor));
		LOGGER.debug("task created: {}", result);
		return result;
	}

	private String serialize(String type, Object descriptor) {
		Optional<ArgumentSerializer> serializer = serializerResolver.resolve(type, descriptor);
		if (serializer.isPresent()) {
			return serializer.get().serialize(descriptor);
		}
		throw new TaskException(String.format("failed to resolve argument serializer, taskType=%s, argument=%s", type, descriptor));
	}
}
